<template>
  <div class="container">
    <div class="left-content">
      <div class="title">
        <div class="top-common-template" 
            :class="{ active: defaultMenuOrTemplate === true }"
            @click="onComOrTemClick('Common')">
            <i class="sc-icon xicon-wenjianjia-xian"></i>
            <span class="common-font">{{ $i18n('template.category.label') }}</span></div>
        <div class="top-common-template"   
            v-show="isShowTemplate"
            :class="{ active: defaultMenuOrTemplate === false }"
            @click="onComOrTemClick('template')">
            <i class="sc-icon xicon-file"></i>
            <span class="common-font">{{ $i18n('template.name.title.lable')}}</span>
          </div>
      </div>
      <Menu v-show="defaultMenuOrTemplate"
        style="flex-grow: 1; overflow: auto"
        @onMenuItemChange="handleMenuItemChange"
        :defaultSelectedKeys="defaultSelectedKeys"
        :menuList="menuList">
      </Menu>
      <Tree  
        v-if="!defaultMenuOrTemplate"
        :type="type"
        :tree-data="treeData" 
        :normalTreeData="normalTreeData"
        :mapData="mapData"
        :data="selectTemplateId"
        @triggerValueChange="triggerValueChange"
        @searchTreeNode="searchTreeNode"
        ref="scTree"></Tree>
      <TagsAdd :isTagsSelected="isTagsSelected" @handleNameClick="handleNameClick" v-show="defaultMenuOrTemplate"> </TagsAdd>
    </div>

    <div class="right-content">
      <iframe :src="rightContentSrc" frameborder="0" width="100%" height="100%"></iframe>
    </div>
  </div>
</template>
<script>
  import Menu from '../../components/menu';
  import TagsAdd from './components/tags-add.vue';
  import { getToDoCountList } from './api';
  import { getUrlSearchParams,getParams } from '../../utils';
  import Tree from '@/components/search-condition/widgets/sc-tree.vue';
  export default {
    components: {
      Menu,
      TagsAdd,
      Tree
    },
    data() {
      return {
        menuList: [],
        defaultSelectedKeys: [],
        rightContentSrc:'',
        isTagsSelected: true,
        type:'template',//类型：模板
        defaultMenuOrTemplate:true,//默认常用还是按模块看
        selectTemplateId:"",//新增选择的模板id
        isShowTemplate:true,//是否显示模板，目前默认模板头部菜单
        urlParamObj:{},//url参数obj记录
        treeData: [],//树数据
        normalTreeData:[],//便于搜索时所用的数据
        mapData: {},//存储树数据的mapData
        commonRightContentSrc:'',//存储 右侧选中url值 用于切换到常用菜单时url
        defaultCommonSelectedKeys:'',//存储 右侧选中值 用于切换到常用菜单时默认key
        recodedClickMenuName:'',//新增记录点击的分类菜单名称
      };
    },
    methods: {
      init() {
        const urlParams = getUrlSearchParams();
        const defaultSelectedKey = `${urlParams.get('fragmentId')}_${urlParams.get(
          'ordinal'
        )}_${urlParams.get('bigTitleIndex')}`;
        this.defaultSelectedKeys = [defaultSelectedKey];
        
        this.initData((menuList) => {
          const item = menuList.find((item) => item.key === defaultSelectedKey);
          this.rightContentSrc = item.url + '&noOperate=1';
          this.commonRightContentSrc = item.url + '&noOperate=1';//新增逻辑 初始化存储最初点击右侧值
          getCtpTop().setWindowTabTitle(item.title, window.self.name, true);
          this.recodedClickMenuName=item.title;
          this.defaultCommonSelectedKeys = this.defaultSelectedKeys;
          this.urlParamObj = getParams(window.location.search);//新增逻辑
          // this.getSwitchCommonOrTemplate();//取浏览器行为 注释掉浏览器行为
        });

       
      },
      initData(callback = () => {}) {
        const spaceId = getUrlSearchParams('spaceId');
        getToDoCountList(spaceId).then((res) => {
          this.menuList = res.data.data.map((item) => {
            return { title: item.name, subTitle: item.count, key: item.id, url: item.url };
          });
          callback(this.menuList);
        });
      },
      handleMenuItemChange({ title, url, key }) {
        this.rightContentSrc = url + '&t=' + Date.now() + '&noOperate=1';
        this.defaultSelectedKeys = [key];
        this.isTagsSelected = false;
        this.commonRightContentSrc = this.rightContentSrc;//点击左侧常用菜单 记录点击的url
        this.defaultCommonSelectedKeys=this.defaultSelectedKeys;//点击左侧常用菜单 记录点击的url的默认key
        getCtpTop().setWindowTabTitle(title, window.self.name, true);
        this.recodedClickMenuName=title;
        this.initData();
      },
      handleNameClick({ labelName, labelId }) {
        let url =
          '/seeyon/apps_res/collaboration/todo-center/all-pending-list/index.html?pageKey=LIST_PENDING_SECTION&spaceId=&uuid=&fragmentId=&ordinal=0&bigTitleIndex=0&section=pendingSection&cacheCountKey=&from=';
        this.rightContentSrc =
          url +
          '&labelId=' +
          labelId +
          '&name=' +
          encodeURIComponent(this.$i18n('label.name') + ':' + labelName) +
          '&noOperate=1';
        this.defaultSelectedKeys = [];
        this.isTagsSelected = true;
        this.selectTemplateId = '';//点击标签时，模板选中节点需要清楚掉
      },
      triggerValueChange(data,value) {
        console.log('选中左侧的模板',data.templatePanel);
        const {
            fragmentId = '',
        } = this.urlParamObj||{};
        if(value){//选中的值
          this.selectTemplateId =value && value.join(',');
        }else{
            this.selectTemplateId = data.templatePanel
            if(data.templatePanel && data.templatePanel.indexOf('C_') === -1){//首次加载不需要转换
              this.selectTemplateId = this.mapData[data.templatePanel].key;
            }
        }
        let url = '/seeyon/apps_res/collaboration/todo-center/all-pending-list/index.html?pageKey=LIST_PENDING_SECTION&spaceId=&uuid=&ordinal=0&bigTitleIndex=0&section=pendingSection&cacheCountKey=&from=';
        this.rightContentSrc = url+'&templatePanel='+data.templatePanel+ '&t=' + Date.now() + '&noOperate=1';
        this.isTagsSelected = false;//点击模板里面的具体模板时，标签选中需要清楚掉
      },
      //新增逻辑 点击常用（分类）还是看模板查看（模板）头部菜单点击事件
      async onComOrTemClick(flag){
        if(flag === 'Common'){
          this.defaultMenuOrTemplate = true;
          this.rightContentSrc = this.commonRightContentSrc;//选中之前点击左侧常用菜单的url
          this.defaultSelectedKeys=this.defaultCommonSelectedKeys;//选中之前 点击左侧常用菜单 默认key
          //this.$refs.scTree.clean();
          this.selectTemplateId = '';//选中分类 清空右侧模板选中节点
          getCtpTop().setWindowTabTitle(this.recodedClickMenuName, window.self.name, true);
        }else{
          this.defaultMenuOrTemplate = false;
          //用户切换分类后浏览器记录用户操作
          this.treeData = await this.getTreeData();
          console.log('获取模板树',this.treeData)
          
          if(this.treeData && this.treeData.length > 0){//有数据时才需要默认选中第一个节点
            this.normalTreeData =  JSON.parse(JSON.stringify(this.treeData));
            this.triggerValueChange(this.defaultTreeFirstNode(this.treeData[0]));//获取树里面的第一个节点并默认选中过滤右侧表格里面的数据
          }
          getCtpTop().setWindowTabTitle(this.$i18n('template.name.title.lable'), window.self.name, true);
        }
        this.saveSwitchCommonOrTemplate(flag)
      },
      async getTreeData() {
        const {
            propertyId = '',
            propertyFrom = '',
            fragmentId = '',
            ordinal = '',
            section = '',
            bigTitleIndex = ''
        } = this.urlParamObj||{};
        const memberId = window._currentUser.id;
        const method ='getTreeData4PendingTemplate';
        const params = {
          memberId,
          getRecent: false // 不获取最近模版
        };
        console.log('params', params);
        const args = `managerMethod=${method}&arguments=${JSON.stringify(params)}`;
        const url = `${
          window._ctxPath
        }/ajax.do?method=ajaxAction&managerName=pendingManager&propertyId=${propertyId}&propertyFrom=${propertyFrom}
        &section=${section}&rnd=${Math.random()}`;
        const data = await  window.axios.post(url, args).then((ret) => ret?.data);
        console.log(this.arrayToTree(data), 'this.arrayToTree(data)');
        return  this.arrayToTree(data);
      },
      arrayToTree(items) {
        // 存放结果集
        let res = [];
        // 判断对象是否有某个属性
        let map = {};

        // 边做map存储，边找对应关系
        for (const i of items) {
          map[i.id] = {
            ...i,
            label: i.name,
            key: i.type ==='template'?i.pId+'_'+i.id:i.id,
            value: i.id,
            children: map[i.id] ? map[i.id].children : []
          };
          let newItem = map[i.id];
          if(i.type ==='template'){//若是具体的模板需要拼接pid+pid来区分最新处理模板和公共模板的具体模板 用于区分选中
            this.mapData[i.pId+'_'+i.id] = newItem;
          }else {
            this.mapData[i.id] = newItem;
          }
         
          if (i.pId === null || i.id === i.pId) {
            res.push(newItem);
          } else {
            if (!map[i.pId]) {
              map[i.pId] = {
                children: []
              };
            }
            map[i.pId].children.push(newItem);
            map[i.pId].scopedSlots = { title: 'folder' };
            if (!newItem.children.length) {
              newItem.scopedSlots = { title: 'doc' };
            }
            //V5-71226有种场景需要适配  比如 分类"category"的顺序是乱序，接口返回0123，但是层级关系0213就调整了就会导致某种场景newItem里面有children但是没有这个属性scopedSlots ，会导致前台显示--
            if(newItem.children.length && newItem.type === 'category' && !newItem.scopedSlots){
              newItem.scopedSlots = { title: 'folder' };
            }
          }
        }
        return res;
      },
      async getRefreshTreeData(){
        this.treeData =  await this.getTreeData();
        this.normalTreeData =  JSON.parse(JSON.stringify(this.treeData))
      },
      //记录浏览器行为
      saveSwitchCommonOrTemplate(flag){
        var  obj ={ }
        obj[window._currentUser.id+'_'+this.urlParamObj.fragmentId]=flag;
        if(!localStorage.getItem('pendingSwitchComOrTemplate')){//首次不存在直接存储
          localStorage.setItem('pendingSwitchComOrTemplate', JSON.stringify(obj));
        }else{//若是存在key直接更新
            var switchComOrTemp = JSON.parse(localStorage.getItem('pendingSwitchComOrTemplate'));
            console.log('switchComOrTemp',switchComOrTemp);
            switchComOrTemp[window._currentUser.id+'_'+this.urlParamObj.fragmentId]=flag;
            localStorage.setItem('pendingSwitchComOrTemplate', JSON.stringify(switchComOrTemp));
        }
       
      },
      //取浏览器行为
      getSwitchCommonOrTemplate(){
        if(localStorage.getItem('pendingSwitchComOrTemplate')){
          let switchComOrTempObj = JSON.parse(localStorage.getItem('pendingSwitchComOrTemplate'));
          if(switchComOrTempObj[window._currentUser.id+'_'+this.urlParamObj.fragmentId]){
            let  switchComOrTemp  = switchComOrTempObj[window._currentUser.id+'_'+this.urlParamObj.fragmentId];
            this.onComOrTemClick(switchComOrTemp);
          }
        }
       
      },
      //默认选中树里面的第一个节点
      defaultTreeFirstNode(node){
        console.log('nodeId',node);
        let targetObj = node;
        let retValue = {};
        retValue.text = targetObj.name;
        if (targetObj.type === 'template') {
          retValue.templatePanel = targetObj.id;
          return retValue;
        }
        if (targetObj.unionIds && targetObj.unionIds.indexOf(',') > -1) {
          retValue.templatePanel = targetObj.unionIds
            .split(',')
            .map((id) => 'C_' + id)
            .join(',');
          return retValue;
        }
        retValue.templatePanel = 'C_' + targetObj.id;
        return retValue;
      },
      searchTreeNode(nodes){
        console.log('nodes',nodes)
        this.treeData = nodes;
      }

    },
    created() {
      this.init();
      window.refreshMenuList = () => {
        this.initData();
        this.getRefreshTreeData();
      };
    },
    beforeDestroy() {
      delete window.refreshMenuList;
    }
  };
</script>
<style>
  @import url('../../assets/css/common.css');
</style>
<style lang="scss" scoped>
  .container {
    display: flex;
    height: 100%;

    .left-content {
      display: flex;
      flex-direction: column;
      height: 100%;
      width: 220px;
      border-right: 1px solid #eceff6;

      .title {
        line-height: 32px;
        //padding-left: 22px;
        margin-bottom: 8px;
        font-size: 14px;
        color: #000000;
        // background: #f9fafc;
        background: #F3F5FB;
        border-radius: 4px;
        margin: 8px 14px;
        display: flex;
        width: 192px;
        height: 32px;
        min-height: 32px;
        font-family:Arial, PingFang SC, Microsoft YaHei, Helvetica, sans-serif, SimSun;
        .top-common-template{
          flex:1;
          padding-right: 4px;
          font-size: 14px;
          margin:4px;
          line-height: 20px;
          padding: 2px 8px;
          cursor:pointer;
          text-align:center;
          color: #666;
        }
        .active {
          color: var(--theme-brand5, #4a9ff2);
          background: #FFFFFF;
          box-shadow: 0 1px 1px 0 #0000000f;
          border-radius: 2px;
          padding: 2px 8px;
          // font-weight: bold;
        }
       .active .common-font{
          font-weight: 600;
        }
        .sc-icon{
          font-size: 14px;
          padding-right: 4px;
        } 
      }
    }

    .right-content {
      height: 100%;
      flex-grow: 1;
      overflow: hidden;
    }
  }
</style>
